/*
 * Copyright (C) 2016 Lokiy(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  　　　　http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.lokiy.core.internal

interface IStore {

    /**
     * Returns the value corresponding to the given [key], or `null` if such a key is not present in the map.
     */
    fun <T> getTag(key: String): T?

    /**
     * Sets a tag associated with this obj and a key.
     * If the given {@code newValue} is {@link Closeable},
     * it will be closed once {@link #clear()}.
     * <p>
     * If a value was already set for the given key, this calls do nothing and
     * returns currently associated value, the given {@code newValue} would be ignored
     * <p>
     * If the ViewModel was already cleared then close() would be called on the returned object if
     * it implements {@link Closeable}. The same object may receive multiple close calls, so method
     * should be idempotent.
     */
    fun <T> setTagIfAbsent(key: String, newValue: T): T
}

@Suppress("FunctionName")
fun DefaultStore(): IStore = DefaultStoreImpl()


private class DefaultStoreImpl : IStore {
    private val mBagOfTags: MutableMap<String, Any> by lazy { mutableMapOf() }

    override fun <T> setTagIfAbsent(key: String, newValue: T): T {
        var previous: T?
        synchronized(mBagOfTags) {
            previous = mBagOfTags[key] as T?
            if (previous == null) {
                mBagOfTags[key] = newValue!!
            }
        }
        return previous ?: newValue
    }


    override fun <T> getTag(key: String): T? {
        synchronized(mBagOfTags) { return mBagOfTags[key] as? T }
    }

}